package com.cjr.mq.cases.config;


import com.cjr.mq.cases.service.OrderService;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
public class MyMessageListener {

    private static final Logger logger = LoggerFactory.getLogger(MyMessageListener.class);
    @Autowired
    private OrderService orderService;

    @RabbitListener(queues = RabbitConfig.DEAD_LETTER_QUEUE, ackMode = "MANUAL")
    public void handleDlxMessage(Message message, Channel channel) {

        // 从队列中取出订单号
        String orderId = new String(message.getBody(), StandardCharsets.UTF_8);
        logger.info("消费者接收到的订单号 【{}】", orderId);
        // 取消订单
        String flag = "cancle";
        orderService.updateOrderStatus(orderId, flag);
        logger.info("该订单【{}】已取消", orderId);

        try {
            // 手动ack，deliveryTag表示消息的唯一标志，multiple表示是否是批量确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
//            System.err.println("已确认消息：" + message);
            logger.info("已确认消息, {}", orderId);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
